import { clsx, type ClassValue } from "clsx";
import { twMerge } from "tailwind-merge";
import { config } from "../config";
export function cn(...inputs: ClassValue[]) {
  return twMerge(clsx(inputs));
}

export async function TestDataGenerator(message: string): Promise<{
  inputImages: string[];
  outputImages: string[];
  chosenModel: string | string[];
} | null> {
  const jsonRegex = /\{.*\}/;
  const jsonString = message.match(jsonRegex)?.[0];

  if (!jsonString) {
    console.log("No JSON found in the message:", message);
    return null;
  }

  try {
    const jsonData = JSON.parse(jsonString);

    // 校验必要字段是否存在
    if (!jsonData.image || !jsonData.vis_files || !jsonData.txt_file) {
      console.log("Invalid JSON format:", jsonData);
      return null;
    }

    const imageUrls: string[] = Array.isArray(jsonData.image)
      ? jsonData.image
      : [jsonData.image];
    const visPathUrls: string[] = Array.isArray(jsonData.vis_files)
      ? jsonData.vis_files
      : [jsonData.vis_files];
    const txtPathUrl: string = jsonData.txt_file;

    // 创建获取 inputImages 的 Promises
    const imageFetchPromises = imageUrls.map(async (url) => {
      const response = await fetch(
        `${config.AI_SERVICE_URL}${config.AI_SERVICE_URL_PREFIX}/get_output_vis`,
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({ path: url }),
        }
      );
      if (!response.ok) {
        throw new Error(
          `Failed to fetch image from ${url}: ${response.status} ${response.statusText}`
        );
      }
      return response.blob();
    });

    // 创建获取 outputImages 的 Promises
    const visPathFetchPromises = visPathUrls.map(async (url) => {
      const response = await fetch(
        `${config.AI_SERVICE_URL}${config.AI_SERVICE_URL_PREFIX}/get_output_vis`,
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({ path: url }),
        }
      );
      if (!response.ok) {
        throw new Error(
          `Failed to fetch vis_files from ${url}: ${response.status} ${response.statusText}`
        );
      }
      return response.blob();
    });

    // 创建获取 outputText 的 Promise
    const txtPathFetchPromise = async () => {
      const response = await fetch(
        `${config.AI_SERVICE_URL}${config.AI_SERVICE_URL_PREFIX}/get_output_txt`,
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({ path: txtPathUrl }),
        }
      );
      if (!response.ok) {
        throw new Error(
          `Failed to fetch txt_file from ${txtPathUrl}: ${response.status} ${response.statusText}`
        );
      }
      return response.json(); // 期望返回JSON对象
    };

    const [inputImageBlobs, outputImageBlobs, outputTextData] =
      await Promise.all([
        Promise.all(imageFetchPromises),
        Promise.all(visPathFetchPromises),
        txtPathFetchPromise(),
      ]);

    // 将 Blob 转换为 Object URL
    const inputImages = inputImageBlobs.map((blob) =>
      URL.createObjectURL(blob)
    );
    const outputImages = outputImageBlobs.map((blob) =>
      URL.createObjectURL(blob)
    );

    // 提取 model 字段
    const chosenModel = outputTextData.model as string | string[];

    return {
      inputImages,
      outputImages,
      chosenModel,
    };
  } catch (error) {
    console.log("TestDataGenerator Error:", error);
    return null;
  }
}

export function TrainDataGenerator(message: string): { reward: number } | null {
  try {
    // 允许等号周围有空格，并增强数字匹配模式
    const match = message.match(/episodic_return\s*=\s*(-?\d+(\.\d+)?)/);
    if (!match) {
      throw new Error("No episodic_return found in message");
    }
    const reward = parseFloat(match[1]);
    if (isNaN(reward)) {
      throw new Error("Invalid number format for episodic_return");
    }
    return { reward };
  } catch (error) {
    console.log("TrainDataGenerator Error:", error);
    return null;
  }
}
